/*
 * HibernateUtil.java
 *
 * $Id: HibernateUtil.java,v 1.3 2009-03-25 08:49:48 mario Exp $
 *
 * Author: Mario García García - Imagos 2007
 */
package org.ceteca.explica.server.util.db;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.ceteca.explica.core.HibernateEntityResolver;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.w3c.dom.Document;

/**
 * Implementation of an Hibernate utility class to encapsulate the Hibernate
 * framework. It will provide access to Hibernate framework utilities and will
 * be in charge of configuring, starting up and shutting down the Hibernate
 * engine.
 * <br/> 
 * Responsibilities: 
 *  <li>
 *   <ul> Configure and startup Hibernate framework. </ul> 
 *   <ul> Provide access to Hibernate Sessions. </ul> 
 *   <ul> Shutdown Hibernate framework. </ul>
 *  </li>
 */
public class HibernateUtil {

	/**
	 * Definition of the unique SessionFactory available in the whole system.
	 */
	private static SessionFactory sessionFactory;

	/**
	 * Configuration of the session factory.
	 * @param cfgFile InputStream, stream opened to the Hibernate configuration file.
	 */
	public static void configHibernate(InputStream cfgFile) {
		Configuration cfg = new Configuration();
		cfg.setEntityResolver(new HibernateEntityResolver());
		Document doc = null;
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			db.setEntityResolver(new HibernateEntityResolver());
			doc = db.parse(cfgFile);
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		
		cfg.configure(doc);
		cfg.createMappings();
		try {
			sessionFactory = cfg.buildSessionFactory();
		} catch (Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		}
	}

	/**
	 * Return the unique SessionFactory to open a new session to manage
	 * the connection to the Database through Hibernate framework. 
	 * @return SessionFactory, Factory for creation of Hibernate sessions.
	 */
	public static SessionFactory getSessionFactory() {
		return sessionFactory;

	}

	/**
	 * Close caches and connection pools of Hibernate framework.
	 *
	 */
	public static void shutdown() {
		getSessionFactory().close();
	}
	
	

	/**
	 * Returns tag Id assigned to CVS source file.
	 */
	public static String getRevision() {
		return "$Id: HibernateUtil.java,v 1.3 2009-03-25 08:49:48 mario Exp $";
	}
}
